using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveState : IFsmState
{
    private Rigidbody2D m_Rig;
    private Entity m_Entity; // 保存实体引用，以便实时读取速度

    public void Enter(Entity entity, params object[] args)
    {
        m_Rig = entity.GetComponent<Rigidbody2D>();
        m_Entity = entity; // 保存实体引用
        
        // 调试信息
        if (m_Rig == null)
        {
            Logger.LogError("MoveState", $"Rigidbody2D component not found on {entity.name}");
        }
        if (entity.MoveComponent == null)
        {
            Logger.LogError("MoveState", $"MoveComponent not found on {entity.name}");
        }
        else
        {
            float speed = entity.MoveComponent.MoveSpeed;
            Logger.Log("MoveState", $"MoveState Enter, speed={speed} for {entity.name}");
        }
    }

    public void Exit(Entity entity, params object[] args)
    {

    }

    public void Process(Entity entity, params object[] args)
    {
        // 检查组件是否存在
        if (m_Rig == null)
        {
            Logger.LogError("MoveState", $"Process: Rigidbody2D is null for {entity.name}");
            return;
        }
        
        // 检查生命值
        long hp = entity.HealthComponent.CurHealth;
        if (hp <= 0)
        {
            entity.FSMComponent.ChangeStatus(FSMType.Dead);
            return;
        }

        // 检查是否有敌人，如果有则攻击
        var enemy = entity.AttackComponent.FindEnemy();
        if (enemy != null)
        {
            entity.FSMComponent.ChangeStatus(FSMType.Attack, enemy);
            return;
        }

        // 检查是否有击退buff，如果有则停止移动
        bool isExist = entity.BuffComponent.ImmuneMask.BuffTagHasAny(BuffTag.Knockback);
        if (isExist)
        {
            return;
        }

        // 实时读取速度，而不是使用缓存值（这样减速效果才能生效）
        float currentSpeed = entity.MoveComponent != null ? entity.MoveComponent.MoveSpeed : 0f;
        
        // 如果速度太小，记录警告
        if (currentSpeed <= 0.01f)
        {
            //Logger.LogWarning("MoveState", $"{entity.name} 速度过小或为0: {currentSpeed}，可能无法移动");
        }
        
        // 执行移动
        Vector2 newPosition = m_Rig.position + Vector2.left * currentSpeed * Time.deltaTime;
        m_Rig.MovePosition(newPosition);
        
        // 调试信息（每5秒输出一次）
        if (Time.time % 5f < Time.deltaTime)
        {
            //Logger.Log("MoveState", $"{entity.name} moving at speed {currentSpeed}, position: {m_Rig.position}");
        }
    }
}